package com.ls.x.activity;

import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.ls.x.R;
import com.ls.x.tool.DatabaseHelper;

public class AlertEditActivity extends Activity {

	private EditText alertModelNameEditText;
	private CheckBox alertModelRingCheckBox;
	private CheckBox alertModelPopupDialogCheckBox;
	private CheckBox alertModelShakeCheckBox;
	private CheckBox alertModelAlarmClockCheckBox;
	private CheckBox alertModelSMSCheckBox;
	private EditText ringAndShakeModelRadioGroup_repetNTimesEditText;
	private EditText SMSPhoneNumberEditText;
	private CheckBox popupDialogContentTitleCheckBox;
	private CheckBox popupDialogContentSummaryCheckBox;
	private CheckBox popupDialogContentLocationCheckBox;

	private RadioButton ringAndShakeModelRadioGroup_untilClosedRadioButton;
	private RadioButton ringAndShakeModelRadioGroup_repetThreeTimesRadioButton;
	private RadioButton ringAndShakeModelRadioGroup_repetSixTimesRadioButton;
	private RadioButton ringAndShakeModelRadioGroup_repetNTimesRadioButton;

	private Button buttonSaveAlertModel;
	private Button buttonCancelAlertModel;

	private RingAndShakeModelRadioGroupChecked ringAndShakeModelRadioGroupChecked;

	public static final int ALERT_MODEL_RING = 0;
	public static final int ALERT_MODEL_POPUP_DIALOG = 1;
	public static final int ALERT_MODEL_SHAKE = 2;
	public static final int ALERT_MODEL_ALARM_CLOCK = 3;
	public static final int ALERT_MODEL_SMS = 4;

	public static final int RING_AND_SHAKE_MODEL_UNTIL_CLOSED = 10;
	public static final int RING_AND_SHAKE_MODEL_REPET_THREE_TIMES = 11;
	public static final int RING_AND_SHAKE_MODEL_REPET_SIX_TIMES = 12;
	public static final int RING_AND_SHAKE_MODEL_REPET_N_TIMES = 13;

	public static final int POPUP_DIALOG_CONTENT_TITLE = 20;
	public static final int POPUP_DIALOG_CONTENT_SUMMARY = 21;
	public static final int POPUP_DIALOG_CONTENT_LOCATION = 22;

	private HashMap<Integer, CheckBox> checkBoxMapForAlertModel = null;
	private HashMap<Integer, CheckBox> checkBoxMapForpopupDialogContentConfig = null;

	private int alertModelId = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_alert_model_edit);
		alertModelNameEditText = (EditText) findViewById(R.id.alertModelNameEditText);

		alertModelRingCheckBox = (CheckBox) findViewById(R.id.alertModelRingCheckBox);
		alertModelPopupDialogCheckBox = (CheckBox) findViewById(R.id.alertModelPopupDialogCheckBox);
		alertModelShakeCheckBox = (CheckBox) findViewById(R.id.alertModelShakeCheckBox);
		alertModelAlarmClockCheckBox = (CheckBox) findViewById(R.id.alertModelAlarmClockCheckBox);
		alertModelSMSCheckBox = (CheckBox) findViewById(R.id.alertModelSMSCheckBox);

		ringAndShakeModelRadioGroup_untilClosedRadioButton = (RadioButton) findViewById(R.id.ringAndShakeModelRadioGroup_untilClosedRadioButton);
		ringAndShakeModelRadioGroup_repetThreeTimesRadioButton = (RadioButton) findViewById(R.id.ringAndShakeModelRadioGroup_repetThreeTimesRadioButton);
		ringAndShakeModelRadioGroup_repetSixTimesRadioButton = (RadioButton) findViewById(R.id.ringAndShakeModelRadioGroup_repetSixTimesRadioButton);
		ringAndShakeModelRadioGroup_repetNTimesRadioButton = (RadioButton) findViewById(R.id.ringAndShakeModelRadioGroup_repetNTimesRadioButton);
		ringAndShakeModelRadioGroup_repetNTimesEditText = (EditText) findViewById(R.id.ringAndShakeModelRadioGroup_repetNTimesEditText);

		SMSPhoneNumberEditText = (EditText) findViewById(R.id.SMSPhoneNumberEditText);

		popupDialogContentTitleCheckBox = (CheckBox) findViewById(R.id.popupDialogContentTitleCheckBox);
		popupDialogContentSummaryCheckBox = (CheckBox) findViewById(R.id.popupDialogContentSummaryCheckBox);
		popupDialogContentLocationCheckBox = (CheckBox) findViewById(R.id.popupDialogContentLocationCheckBox);

		buttonSaveAlertModel = (Button) findViewById(R.id.buttonSaveAlertModel);
		buttonCancelAlertModel = (Button) findViewById(R.id.buttonCancelAlertModel);

		HashMap<Integer, RadioButton> radioButtonMap = new HashMap<Integer, RadioButton>();

		radioButtonMap.put(RING_AND_SHAKE_MODEL_UNTIL_CLOSED,
				ringAndShakeModelRadioGroup_untilClosedRadioButton);
		radioButtonMap.put(RING_AND_SHAKE_MODEL_REPET_THREE_TIMES,
				ringAndShakeModelRadioGroup_repetThreeTimesRadioButton);
		radioButtonMap.put(RING_AND_SHAKE_MODEL_REPET_SIX_TIMES,
				ringAndShakeModelRadioGroup_repetSixTimesRadioButton);
		radioButtonMap.put(RING_AND_SHAKE_MODEL_REPET_N_TIMES,
				ringAndShakeModelRadioGroup_repetNTimesRadioButton);

		checkBoxMapForAlertModel = new HashMap<Integer, CheckBox>();
		checkBoxMapForAlertModel.put(ALERT_MODEL_RING, alertModelRingCheckBox);
		checkBoxMapForAlertModel.put(ALERT_MODEL_POPUP_DIALOG,
				alertModelPopupDialogCheckBox);
		checkBoxMapForAlertModel
				.put(ALERT_MODEL_SHAKE, alertModelShakeCheckBox);
		checkBoxMapForAlertModel.put(ALERT_MODEL_ALARM_CLOCK,
				alertModelAlarmClockCheckBox);
		checkBoxMapForAlertModel.put(ALERT_MODEL_SMS, alertModelSMSCheckBox);

		ringAndShakeModelRadioGroupChecked = new RingAndShakeModelRadioGroupChecked(
				radioButtonMap);

		checkBoxMapForpopupDialogContentConfig = new HashMap<Integer, CheckBox>();
		checkBoxMapForpopupDialogContentConfig.put(POPUP_DIALOG_CONTENT_TITLE,
				popupDialogContentTitleCheckBox);
		checkBoxMapForpopupDialogContentConfig
				.put(POPUP_DIALOG_CONTENT_SUMMARY,
						popupDialogContentSummaryCheckBox);
		checkBoxMapForpopupDialogContentConfig.put(
				POPUP_DIALOG_CONTENT_LOCATION,
				popupDialogContentLocationCheckBox);

		buttonSaveAlertModel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String alertModelName = alertModelNameEditText.getText()
						.toString();

				String alertModelStr = getCheckBoxCheckedString(checkBoxMapForAlertModel);

				String SMSPhoneNumber = SMSPhoneNumberEditText.getText()
						.toString();

				String popupDialogContentConfigStr = getCheckBoxCheckedString(checkBoxMapForpopupDialogContentConfig);
				;

				String ringAndShakeModelStr = null;

				if (ringAndShakeModelRadioGroupChecked
						.getLastCheckedRadioButtonId() == RING_AND_SHAKE_MODEL_REPET_N_TIMES) {
					if (ringAndShakeModelRadioGroup_repetNTimesEditText
							.getText().length() == 0) {
						Toast.makeText(
								AlertEditActivity.this,
								getString(R.string.alert_model_edit_activity_toast_not_set_repet_n_times_edittext),
								500).show();
						return;
					}
					ringAndShakeModelStr = ringAndShakeModelRadioGroupChecked
							.getLastCheckedRadioButtonId()
							+ ","
							+ ringAndShakeModelRadioGroup_repetNTimesEditText
									.getText().toString();
				} else {
					ringAndShakeModelStr = ringAndShakeModelRadioGroupChecked
							.getLastCheckedRadioButtonId() + "";
				}

				if (alertModelName == null || alertModelName.equals("")
						|| alertModelStr == null || alertModelStr.equals("")
						|| ringAndShakeModelStr == null
						|| ringAndShakeModelStr.equals("")
						|| SMSPhoneNumber == null || SMSPhoneNumber.equals("")
						|| popupDialogContentConfigStr == null
						|| popupDialogContentConfigStr.equals("")) {

					Toast.makeText(
							AlertEditActivity.this,
							getString(R.string.alert_model_edit_activity_toast_alert_model_incomplete_information),
							500).show();
					return;
				}

				if (alertModelId == 0) {

					DatabaseHelper databaseHelper = DatabaseHelper
							.getDBhelper(AlertEditActivity.this);
					SQLiteDatabase db = databaseHelper.getReadableDatabase();
					Cursor cursor = db.rawQuery(
							"select * from remind_mode where name='"
									+ alertModelName + "'", null);
					if (cursor.getCount() != 0) {
						Toast.makeText(
								AlertEditActivity.this,
								getString(R.string.alert_model_edit_activity_toast_reduplicate_alert_model_name),
								500).show();
						return;
					}

					db.close();

					db = databaseHelper.getWritableDatabase();
				}

				if (alertModelId != 0) {

					DatabaseHelper databaseHelper = DatabaseHelper
							.getDBhelper(AlertEditActivity.this);
					SQLiteDatabase db = databaseHelper.getReadableDatabase();

					db.execSQL("update remind_mode set name='" + alertModelName
							+ "',mode='" + alertModelStr + "',remind_times='"
							+ ringAndShakeModelStr + "',sms_number='"
							+ SMSPhoneNumber + "',alert_content='"
							+ popupDialogContentConfigStr + "' " + "where id="
							+ alertModelId);
					Toast.makeText(
							AlertEditActivity.this,
							getString(R.string.alert_model_edit_activity_toast_update_alert_model_success),
							500).show();
					db.close();
					databaseHelper.close();
				} else {

					DatabaseHelper databaseHelper = DatabaseHelper
							.getDBhelper(AlertEditActivity.this);
					SQLiteDatabase db = databaseHelper.getReadableDatabase();

					db.execSQL("insert into remind_mode(name,mode,remind_times,sms_number,alert_content) values('"
							+ alertModelName
							+ "','"
							+ alertModelStr
							+ "','"
							+ ringAndShakeModelStr
							+ "','"
							+ SMSPhoneNumber
							+ "','" + popupDialogContentConfigStr + "')");

					Toast.makeText(
							AlertEditActivity.this,
							getString(R.string.alert_model_edit_activity_toast_create_alert_model_success),
							500).show();

					db.close();
					databaseHelper.close();
				}

				Intent in = new Intent();
				setResult(1, in);
				finish();
			}
		});

		buttonCancelAlertModel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent in = new Intent();
				setResult(0, in);
				finish();
			}
		});

		Intent intent = getIntent();
		int action = intent.getIntExtra("action", 0);
		Bundle bunde = intent.getExtras();

		switch (action) {
		case ContentEditActivity.INTENT_REQUEST_CODE_FOR_START_REMIND_MODEL_EDIT_ACTIVITY_EDIT_ACTION: {
			String id = bunde.getString("id");
			String name = bunde.getString("name");
			String mode = bunde.getString("mode");
			String remindTimes = bunde.getString("remindTimes");
			String smsNumber = bunde.getString("smsNumber");
			String alertContent = bunde.getString("alertContent");

			alertModelId = Integer.parseInt(id);

			alertModelNameEditText.setText(name);
			checkCheckBoxs(checkBoxMapForAlertModel, mode);

			String[] keysStr = remindTimes.split(",");
			if (keysStr.length > 1) {
				ringAndShakeModelRadioGroup_repetNTimesEditText
						.setText(keysStr[1]);
			}
			switch (Integer.parseInt(keysStr[0])) {
			case RING_AND_SHAKE_MODEL_UNTIL_CLOSED:
				ringAndShakeModelRadioGroup_untilClosedRadioButton
						.setChecked(true);
				break;
			case RING_AND_SHAKE_MODEL_REPET_THREE_TIMES:
				ringAndShakeModelRadioGroup_repetThreeTimesRadioButton
						.setChecked(true);
				break;
			case RING_AND_SHAKE_MODEL_REPET_SIX_TIMES:
				ringAndShakeModelRadioGroup_repetSixTimesRadioButton
						.setChecked(true);
				break;
			case RING_AND_SHAKE_MODEL_REPET_N_TIMES:
				ringAndShakeModelRadioGroup_repetNTimesRadioButton
						.setChecked(true);
				break;
			}

			SMSPhoneNumberEditText.setText(smsNumber);
			checkCheckBoxs(checkBoxMapForpopupDialogContentConfig, alertContent);
		}
		}

	}

	/**
	 * 
	 * @author sunwaylife This inner class is used for dealing with
	 *         RadioButtonGroup,make RadioButtons mutual exclusion.
	 */
	class RingAndShakeModelRadioGroupChecked {
		private HashMap<Integer, RadioButton> radioButtonMap;
		private RadioButton lastCheckedRadioButton = null;
		private int lastCheckedRadioButtonId = 0;
		private int key = 0;

		public RingAndShakeModelRadioGroupChecked(
				HashMap<Integer, RadioButton> radioButtonMap) {
			this.radioButtonMap = radioButtonMap;
			radioButtonMutualExclusionCheck();
		}

		public void radioButtonMutualExclusionCheck() {

			for (int key : radioButtonMap.keySet()) {
				this.key = key;
				RadioButton radioButton = radioButtonMap.get(key);
				radioButton
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {
							private int myselfId = RingAndShakeModelRadioGroupChecked.this.key;

							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {

								Log.d("sunway", isChecked + ":" + myselfId);
								if (isChecked) {

									if (lastCheckedRadioButton != null) {
										lastCheckedRadioButton
												.setChecked(false);
									}
									lastCheckedRadioButton = (RadioButton) buttonView;
									lastCheckedRadioButtonId = myselfId;
									Log.d("sunway", "lastCheckedRadioButtonId"
											+ ":" + myselfId);
								}

							}
						});
			}

		}

		public int getLastCheckedRadioButtonId() {
			return lastCheckedRadioButtonId;
		}

	}

	/**
	 * 
	 * @param checkBoxMap
	 *            The map stores CheckBoxViews,map's key is Integer variable，and
	 *            CheckBox is value
	 * @return checkBoxMap key's string,separator is comma symbol
	 */
	private String getCheckBoxCheckedString(
			HashMap<Integer, CheckBox> checkBoxMap) {
		StringBuilder stringBuilder = new StringBuilder();
		for (int checkBoxId : checkBoxMap.keySet()) {
			CheckBox checkBox = checkBoxMap.get(checkBoxId);
			if (checkBox.isChecked()) {
				stringBuilder.append(checkBoxId).append(",");
			}
		}

		return stringBuilder.toString();
	}

	private void checkCheckBoxs(HashMap<Integer, CheckBox> checkBoxMap,
			String checkedCheckBoxKeysStr) {

		String[] checkBoxKeyStrArray = checkedCheckBoxKeysStr.split(",");

		for (String keyStr : checkBoxKeyStrArray) {
			int key = Integer.parseInt(keyStr);
			CheckBox checkBox = checkBoxMap.get(key);
			checkBox.setChecked(true);
		}
	}
}
